package com.haoxin.ai_course.common.base;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haoxin.ai_course.common.utils.DateUtil;
import com.haoxin.ai_course.common.utils.MPPageConvert;
import com.haoxin.ai_course.modules.sys.entity.SysUser;
import com.haoxin.ai_course.modules.sys.entity.SysUserToken;
import com.haoxin.ai_course.modules.sys.service.SysUserTokenService;

/**
 * Controller公共组件
 */

public abstract class AbstractController {
	@Autowired
	protected MPPageConvert mpPageConvert;
	@Autowired
	SysUserTokenService  sysUserTokenService;
	protected SysUser getUser() throws AuthenticationException {
		Object principal = SecurityUtils.getSubject().getPrincipal();
		if (principal == null){
			QueryWrapper<SysUserToken> queryWrapper = new QueryWrapper<SysUserToken>();
		    String date = 	DateUtil.getNowDate("yyyy-MM-dd HH:mm:ss");
			queryWrapper.le("expire_time", date);
			Integer deleteResult  = sysUserTokenService.removeAllToken(queryWrapper);
			System.out.println("删除无效token result:"+deleteResult);
			throw new IncorrectCredentialsException("token失效001，请重新登录");
		}
		return (SysUser) principal;
	}

	protected Long getUserId() {
		return getUser().getUserId();
	}
}
